package com.thinkit.bigdata.web.service.impl.perCenter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Strings;
import com.thinkit.bigdata.core.util.es.ESUtil;
import com.thinkit.bigdata.web.coremet.SystemStatic;
import com.thinkit.bigdata.web.model.BaseEntity;
import com.thinkit.bigdata.web.model.bus.BusWorkExample;
import com.thinkit.bigdata.web.model.bus.BusWorkWithBLOBs;
import com.thinkit.bigdata.web.model.config.SysArea;
import com.thinkit.bigdata.web.model.es.audioEs.Source;
import com.thinkit.bigdata.web.model.es.audioEs.WorkScores;
import com.thinkit.bigdata.web.model.result.HtmlResult;
import com.thinkit.bigdata.web.service.bus.BusWorkService;
import com.thinkit.bigdata.web.service.perCenter.PerCenterService;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 *
 * Created by hccl on 2018/9/4.
 */
@Service
public class perCenterServiceImpl implements PerCenterService {

    private static Logger logger = Logger.getLogger(perCenterServiceImpl.class);

    @Resource
    private ESUtil esUtil;

    @Resource
    private BusWorkService busWorkService;

    @Override
    public List<BusWorkWithBLOBs> getWorks(String workId) {
        //任务条件组装
        List<BusWorkWithBLOBs> works = new ArrayList<>();
        if (!Strings.isNullOrEmpty(workId)) {
            BusWorkWithBLOBs busWork = busWorkService.selectByPrimaryKey(Long.parseLong(workId));
            if (busWork != null) {
                works.add(busWork);
            }
        } else {
            SysArea area = (SysArea) SecurityUtils.getSubject().getSession().getAttribute("areaInfo");
            if (area != null) {
                works.addAll(busWorkService.selectByCode(area.getCode()));
            }
        }
        return works;
    }

    @Override
    public List<BusWorkWithBLOBs> getWorksByTime() throws UnknownHostException {
        //任务条件组装
        List<BusWorkWithBLOBs> works = new ArrayList<>();
        SysArea area = (SysArea) SecurityUtils.getSubject().getSession().getAttribute("areaInfo");
        if (area != null) {
            BusWorkExample example = new BusWorkExample();
            BusWorkExample.Criteria criteria = example.createCriteria();
            criteria.andProvincecodeEqualTo(area.getCode());
            criteria.andProstatusGreaterThanOrEqualTo(BaseEntity.TASK_PROSTATUS_START);
            works.addAll(busWorkService.selectByExample(example));
        }
        //根据数据权限过滤work
        List<BusWorkWithBLOBs> workList = new ArrayList<>();
        workList = esUtil.taskListQ(workList, works);
        //排除过期的任务
        List<BusWorkWithBLOBs> workArrayList = new ArrayList<>();
        for (BusWorkWithBLOBs work : workList) {
            if (work.getProstatus() == BaseEntity.TASK_PROSTATUS_TEST_OVER) {
                String daysRemaining = esUtil.taskIs("【首页代办任务】", work);
                if (!daysRemaining.equals("-")) {
                    if (Integer.parseInt(daysRemaining) > 0) {
                        workArrayList.add(work);
                    }
                }
            } else {
                workArrayList.add(work);
            }
        }
        return workArrayList;
    }

    @Override
    public BoolQueryBuilder getQuery(HttpServletRequest request, String logTxt) {
        String workId = request.getParameter("workId");//质检任务名称
        String proStatus = request.getParameter("proStatus");//质检状态
        String proFlag = request.getParameter("proFlag");//质检属性  0系统 1人工
        String seatId = request.getParameter("seatId");//坐席工号
        logger.info(logTxt + "workId = " + workId);
        logger.info(logTxt + "proStatus = " + proStatus);
        logger.info(logTxt + "proFlag = " + proFlag);
        logger.info(logTxt + "seatId = " + seatId);
        String provinceCode = null;//省份
        SysArea area = (SysArea) SecurityUtils.getSubject().getSession().getAttribute("areaInfo");
        if (area != null) {
            provinceCode = area.getCode();
        }
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        //数据权限
        esUtil.formatQ(boolQuery, seatId);
        //待办任务 数据查询条件
        esUtil.taskFormatQ(boolQuery, proStatus, workId, proFlag);
        //代办任务 随录信息条件
        esUtil.taskFormVoice(boolQuery, request, logTxt);
        if (!Strings.isNullOrEmpty(provinceCode)) {
            boolQuery.must(QueryBuilders.matchQuery("voiceInfo.provinceCode", provinceCode));
        }
        return boolQuery;
    }

    @Override
    public HtmlResult getDataList(HttpServletRequest request) {
        String workId = request.getParameter("workId");//质检任务名称
        if (Strings.isNullOrEmpty(workId)) {
            return HtmlResult.failure("请选择任务");
        }
        String pageNum = request.getParameter("pageNum");//起始页
        String pageSize = request.getParameter("pageSize");//每页条数
        String sortName = request.getParameter("sortName");//录音流水
        String sortOrder = request.getParameter("sortOrder");//录音流水
        BoolQueryBuilder boolQuery = getQuery(request, "【获取代办任务信息列表】");
        String[] includes = new String[]
                {
                        "serialNumber",
                        "voiceInfo",
                        "workScores"
                };
        List<String> docList = SystemStatic.crud.queryMapQBuilderRetRuleAndWork(
                SystemStatic.AUDIO_ES_INDEX,
                SystemStatic.AUDIO_ES_TYPE,
                Integer.parseInt(pageNum),
                Integer.parseInt(pageSize),
                boolQuery,
                SystemStatic.crud.formatCloumn(sortName, SystemStatic.AUDIO_ES_INDEX),
                sortOrder,
                includes
        );
        logger.info("获取数据条数为：" + docList.size());
        return HtmlResult.success(
                esUtil.formatModel(docList, workId),
                SystemStatic.crud.queryQBuilderAllByMes(SystemStatic.AUDIO_ES_INDEX, SystemStatic.AUDIO_ES_TYPE, boolQuery)
        );
    }

    @Override
    public HtmlResult getMes(HttpServletRequest request) {
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        String workId = request.getParameter("workId");
        esUtil.taskTitleQ(boolQuery, workId);
        int count = SystemStatic.crud.queryQBuilderAllByMes(SystemStatic.AUDIO_ES_INDEX, SystemStatic.AUDIO_ES_TYPE, boolQuery);
        logger.info("获取数据条数为：" + count);
        return HtmlResult.success(count);
    }

    @Override
    public HtmlResult updateDataBySer(HttpServletRequest request) throws IOException {
        String resMap = request.getParameter("resMap");
        List<Map<String, String>> boxList = new ArrayList<>();
        ObjectMapper objectMapper  = new ObjectMapper();
        if(!Strings.isNullOrEmpty(resMap)){
            boxList = objectMapper.readValue(resMap, objectMapper.getTypeFactory().constructCollectionType(List.class,Map.class));
        }
        List<Source> sourceList = new ArrayList<>();
        for (Map<String, String> map : boxList) {
            Source source = esUtil.getSourceBySerialNumber(map.get("serialNumber"));
            for (WorkScores work : source.getWorkScores()) {
                if (map.get("workId").equals(work.getWorkId().toString())) {
                    int proStatus = work.getProStatus();
                    if (proStatus == BaseEntity.BIG_WORK_PROSTATUS_QUALITY_YES_0) {
                        work.setProStatus(BaseEntity.BIG_WORK_PROSTATUS_READ_YES_10);
                    }
                }
            }
            sourceList.add(source);
        }
        return esUtil.updateSources(sourceList);
    }
}
